package com.laixu.estore.service;

import com.laixu.estore.bean.dto.OrderCreateDTO;
import com.laixu.estore.bean.extend.OrderExtend;
import com.laixu.estore.bean.pojo.Order;
import com.laixu.estore.bean.pojo.OrderItem;
import com.laixu.estore.bean.pojo.Shopcar;
import com.laixu.estore.bean.vo.OrderInfoVO;
import com.laixu.estore.dao.BookDao;
import com.laixu.estore.dao.OrderDao;
import com.laixu.estore.dao.OrderItemDao;
import com.laixu.estore.dao.ShopCarDao;
import com.laixu.estore.util.BeanCopyUtils;
import com.sun.org.apache.xpath.internal.operations.Or;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class OrderService {
    private final OrderDao orderDao;
    private final OrderItemDao orderItemDao;
    private final ShopCarDao shopCarDao;
    private final BookDao bookDao;

    public void createOrder(OrderCreateDTO orderCreateDTO, int userId) {
        List<Integer> shopCarIds = orderCreateDTO.getShopCarIds();
        // 1.创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setReceiveUsername(orderCreateDTO.getReceiveUsername());
        order.setReceiveAddress(orderCreateDTO.getReceiveAddress());
        order.setReceivePhone(orderCreateDTO.getReceivePhone());
        orderDao.insert(order);
        // 2.创建订单项 orderId bookId num
        for (Integer shopCarId : shopCarIds) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            // 根据购物车id查出bookId和num
            Shopcar shopcar = shopCarDao.getById(shopCarId);
            orderItem.setBookId(shopcar.getBookId());
            orderItem.setNum(shopcar.getNum());
            orderItemDao.insert(orderItem);
            // 3.移除指定购物车 循环写根据id删除 11 12
            shopCarDao.deleteById(shopCarId);
            // 4.商品扣减库存
            bookDao.updateStore(shopcar.getBookId(),shopcar.getNum());
        }
        // 3.移除指定购物车 循环写根据id删除 11 12
//        shopCarDao.deleteByIds(shopCarIds);
        // 4.商品扣减库存
//        bookDao.updateStore(bookIds);
    }

    // OrderInfoVO 组装页面需要的数据 订单 订单项 书籍 用户
    // OrderExtend 订单拓展 OrderExtend extends Order
    // 拥有原来的订单信息 BookExtend extends Book
    // 订单项信息 List<OrderItem> Category
    public List<OrderInfoVO> orderList(int userId) {
        // 查到了订单和订单项的数据
        List<OrderExtend> list = orderDao.selectOrderDetailByUserId(userId);
        for (OrderExtend orderExtend : list) {
            orderExtend.genPrice();
        }
        // OrderInfoVO和OrderExtend属性是一样的，所以直接复制
        List<OrderInfoVO> vos = BeanCopyUtils.copyBeanList(list, OrderInfoVO.class);
        return vos;
    }
}